// eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks'
import { defineConfig, globalIgnores } from 'eslint/config'
import globals from 'globals'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { fixupConfigRules } from '@eslint/compat'
import { FlatCompat } from '@eslint/eslintrc'
import js from '@eslint/js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
})

export default defineConfig([
  // 全局忽略
  globalIgnores([
    'src/**/*-test.js',
    'src/public',
    'src/locales/_build/',
    'src/locales/**/*.js',
    'docs/**/*.js',
    'src/.umi*/**/*',
    './*.{mjs,js,ts}',
  ]),

  // 主配置：全部通过 compat 引入，避免手动 plugins
  ...fixupConfigRules(
    compat.extends(
      'eslint-config-alloy',
      'eslint-config-alloy/react',
      'eslint-config-alloy/typescript',
      'plugin:import/recommended',
      'plugin:import/typescript'
      // 注意：不要加 "prettier"，因为 alloy 已集成，且 flat config 中需特殊处理
    )
  ),

  // TS 文件专属规则
  {
    files: ['**/*.{js,jsx,ts,tsx}'],
    plugins: {
      'react-hooks': reactHooks,
    },
    languageOptions: {
      globals: {
        ...globals.browser,
      },
      ecmaVersion: 13,
      sourceType: 'script', // 注意：React 项目通常用 "module"
    },
    settings: {
      react: {
        version: 'detect', // 👈 自动检测 node_modules 中的 React 版本
      },
      'import/resolver': {
        typescript: {
          project: './tsconfig.json', // 指向你的 tsconfig
        },
        node: true,
      },
    },
    rules: {
      'react-hooks/rules-of-hooks': 'error',
      'react-hooks/exhaustive-deps': 'warn', // 或 0/1/2
      '@typescript-eslint/explicit-member-accessibility': 'error',
      'prefer-const': 'warn',
      '@typescript-eslint/no-unused-vars': 0,
      '@typescript-eslint/no-require-imports': 0,
      'react/jsx-no-useless-fragment': 0,
      'react/no-unknown-property': ['error', { ignore: ['css'] }],
      'react/no-unstable-nested-components': ['error', { allowAsProps: true }],
      'jsx-a11y/anchor-is-valid': 0,
      'import/no-duplicates': 0,
      'import/no-named-as-default-member': 0,
      'import/order': 0,
      'import/no-unresolved': [1, { ignore: ['^@/', '^api'] }],
      'prefer-destructuring': [1, { object: true, array: false }],
      '@typescript-eslint/explicit-member-accessibility': 'off',
    },
  },
])
